import router from "@/routers/index";
import { LOGIN_URL } from "@/config";
import { RouteRecordRaw } from "vue-router";
import { ElNotification } from "element-plus";
import { useUserStore } from "@/stores/modules/user";
import { useAuthStore } from "@/stores/modules/auth";

import { getMenuTreeAll, getMenuIds } from "@/api/modules/menu";

// 引入 views 文件夹下所有 vue 文件
const modules = import.meta.glob("@/views/**/*.vue");

// let menuData: menuObject[] = [];
let myRoutes: any = [];
/**
 * @description 初始化动态路由
 */
export const initDynamicRouter = async () => {
  const userStore = useUserStore();
  const authStore = useAuthStore();

  let menuArr: any[] = [];
  try {
    // 1.获取菜单列表 && 按钮权限列表
    await authStore.getAuthMenuList();
    await authStore.getAuthButtonList();

    // 2.判断当前用户有没有菜单权限
    if (!authStore.authMenuListGet.length) {
      ElNotification({
        title: "无权限访问",
        message: "当前账号无任何菜单权限，请联系系统管理员！",
        type: "warning",
        duration: 3000
      });
      userStore.setToken("");
      router.replace(LOGIN_URL);
      return Promise.reject("No permission");
    }

    // 动态路由2
    // 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getSpecList"
    const getTableList = async () => {
      // 所有菜单
      const myMenuData = await getMenuTreeAll();
      authStore.setMenuArr(myMenuData);
      // 用户菜单id
      const MenuIds = await getMenuIds(Number(localStorage.getItem("menuId")));
      // 过滤菜单
      const newRouterId = filterMenuList(myMenuData.data, MenuIds.data);
      // 处理路由菜单
      myRoutes = myFilterAsyncRoutes(newRouterId);

      // 添加首页
      myRoutes.unshift({
        path: "/home/index",
        name: "home",
        component: () => import("@/views/home/index.vue"),
        meta: {
          icon: "HomeFilled",
          title: "首页",
          isLink: "",
          isHide: false,
          isFull: false,
          isAffix: true,
          isKeepAlive: false
        }
      });
      // menuData = [...myRoutes];
      // menuData = myRoutes;
      // console.log(myRoutes, "myRoutes22222222");
      // 调用递归函数来添加路由
      addRoutesRecursively(myRoutes);
    };
    await getTableList();

    // 过滤菜单
    function filterMenuList(menuList, idsToKeep) {
      return menuList.reduce((acc, item) => {
        const newItem = { ...item };

        if (idsToKeep.includes(item.id)) {
          // 保留当前项
          if (item.children && item.children.length > 0) {
            // 递归过滤子节点
            newItem.children = filterMenuList(item.children, idsToKeep);
          }
          acc.push(newItem);
        } else if (item.children && item.children.length > 0) {
          // 递归过滤子节点
          newItem.children = filterMenuList(item.children, idsToKeep);
          if (newItem.children.length > 0) {
            // 只保留有子节点的项
            acc.push(newItem);
          }
        }

        return acc;
      }, []);
    }

    // 处理路由菜单
    function myFilterAsyncRoutes(menuList) {
      // 请求当前用户菜单权限 getUserMenuIds
      const obj = menuList.filter(menu => {
        // 没有不执行
        if (menu.type === 0) {
          const url = menu.url.startsWith("/") ? menu.url : "/" + menu.url;
          menu.component = modules["/src/views" + url + ".vue"];
          menu.path = url;
          menu.meta = { title: menu.name, isAffix: false, isFull: false, isHide: false, isKeepAlive: false, isLink: "" };
          menu.meta.icon = menu.icon ? "Menu" : "Menu";
          menuArr.push({
            component: url,
            path: url,
            meta: menu.meta
          });
        } else {
          let url = menu.url.startsWith("/") ? menu.url : "/" + menu.url;
          if (url == "/sys/menu") {
            url = "/sys/sysMenu";
          }
          menu.path = url;
          menu.meta = Object.assign(
            {},
            { title: menu.name, isAffix: false, isFull: false, isHide: false, isKeepAlive: false, isLink: "" }
          );
          menu.meta.icon = menu.icon ? "Menu" : "Menu";
          menu.component = modules["/src/views" + url + ".vue"];
          menuArr.push({
            component: url,
            path: url,
            meta: menu.meta
          });
        }
        // 递归处理子菜单
        if (menu.children && menu.children.length) {
          menu.children = myFilterAsyncRoutes(menu.children);
        }
        return true;
      });
      // console.log(menuList, "menuList");
      return obj;
    }

    // 添加路由
    function addRoutesRecursively(routes) {
      routes.forEach(route => {
        if (route.type === 0) {
          const newRoute = Object.assign({}, route);
          router.addRoute(newRoute as unknown as RouteRecordRaw);
        } else {
          // 命名问题
          if (route.url == "/sys/menu") {
            route.url = "/sys/sysMenu";
          }
          router.addRoute("layout", route as unknown as RouteRecordRaw);
        }
        // 如果有子路由，则递归添加子路由
        if (route.children && route.children.length > 0) {
          addRoutesRecursively(route.children);
        }
      });
    }
    // console.log(authStore.flatMenuListGet, "authStore.flatMenuListGet 原动态菜单");

    // 3.添加动态路由
    authStore.flatMenuListGet.forEach(item => {
      item.children && delete item.children;
      if (item.component && typeof item.component == "string") {
        item.component = modules["/src/views" + item.component + ".vue"];
      }
      if (item.meta.isFull) {
        router.addRoute(item as unknown as RouteRecordRaw);
      } else {
        router.addRoute("layout", item as unknown as RouteRecordRaw);
      }
    });

    // console.log(menuArr, "menuArr11111111");
    authStore.addAuthMenuList(myRoutes);
    // authStore.addAuthMenuList2(menuArr);
  } catch (error) {
    // 当按钮 || 菜单请求出错时，重定向到登陆页
    userStore.setToken("");
    router.replace(LOGIN_URL);
    return Promise.reject(error);
  }
  // console.log(menuArr, "树动态菜单----"); //
  // console.log(router.getRoutes(), "添加后动态菜单----"); //
};

// interface menuObject {
//   id: number;
//   pid: number;
//   status: number;
//   type: number;
//   code?: string;
//   name: string;
//   identification?: any;
//   url: string;
//   icon: string;
//   memo: string;
//   sort: number;
//   creator_id: number;
//   updater_id: number;
//   created_at: string;
//   updated_at: string;
//   children: Child[];
//   path: string;
//   meta: Meta;
//   component: any;
// }

// interface Child {
//   id: number;
//   pid: number;
//   status: number;
//   type: number;
//   code?: string;
//   name: string;
//   identification?: any;
//   url: string;
//   icon: string;
//   memo?: string;
//   sort?: number;
//   creator_id: number;
//   updater_id: number;
//   created_at: string;
//   updated_at: string;
//   children: any[];
//   path: string;
//   meta: Meta;
//   component: string;
// }

// interface Meta {
//   title: string;
//   isAffix: boolean;
//   isFull: boolean;
//   isHide: boolean;
//   isKeepAlive: boolean;
//   isLink: string;
//   icon: string;
// }
